package com.android.baseconfig.common.utils;

import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

/**
 * @author lei
 * @description StringUtils
 * @date 2018/5/5
 */
public final class StringUtils {
    private StringUtils() {
    }

    // 报文utf-8格式
    public static final String DEFAULT_PARAMS_ENCODING = "UTF-8";

    private static final Pattern EMAILER = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    private static final String HEXSTRING = "0123456789ABCDEF";

    /**
     * 判断给定字符串是否空白串? 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     *
     * @param input
     * @return boolean
     */
    public static boolean isEmpty(String input) {
        if (input == null || "".equals(input)) {
            return true;
        }

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0) {
            return false;
        }

        return EMAILER.matcher(email).matches();
    }

    public static boolean isStringEmpty(String string) {

        return TextUtils.isEmpty(string);
    }

    public static boolean isNull(String strSource) {
        return strSource == null || "".equals(strSource.trim());
    }

    /**
     * 替换字符.按照{i}和数组顺序进行一一替换.<br>
     *
     * @param text
     * @param replaceValue
     * @return String
     */
    public static String getI18nString(String text, String[] replaceValue) {
        // 如果text不为空，并且替换内容长度大于0
        if (null != text && !text.isEmpty() && replaceValue.length > 0) {
            for (int i = 0; i < replaceValue.length; i++) {
                text = text.replace("{" + i + "}", replaceValue[i]);
            }
        }
        return text;
    }

    /**
     * 获取参数的值，如果为空则返""
     *
     * @param str
     * @return String
     */
    public static String getValue(String str) {
        return null == str ? "" : str;
    }

    /**
     * 将字符串编码用16进制数字,适用于所有字符（包括中文）
     *
     * @param str
     * @return String
     */
    public static String encode(String str) {
        if (isEmail(str)) {
            return "";
        }
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes(Charset.forName(DEFAULT_PARAMS_ENCODING));
        return encode(bytes);
    }

    /**
     * byte 转换16进制<br>
     *
     * @param bytes
     * @return String
     */
    public static String encode(byte[] bytes) {
        if (null == bytes) {
            return "";
        }
        // 根据默认编码获取字节数组
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(HEXSTRING.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(HEXSTRING.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    /**
     * 16进制转换成字符串
     *
     * @param bytes
     * @return
     */
    public static byte[] decode(String bytes) {
        if (isEmpty(bytes)) {
            return new byte[0];
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
        // 将每2个16进制整数组装成一个字符
        for (int i = 0; i < bytes.length(); i += 2) {
            baos.write((HEXSTRING.indexOf(bytes.charAt(i)) << 4 | HEXSTRING.indexOf(bytes.charAt(i + 1))));
        }
        return baos.toByteArray();
    }

    public static byte[] hexStringToBytes(String hexString) {
        hexString = hexString.toUpperCase(Locale.getDefault());
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) HEXSTRING.indexOf(c);
    }

    /**
     * 将时间转成对应的style格式
     *
     * @param style yyyy-MM-dd|yyyyMMdd_hhmmss|yyyy-MM-dd hh:mm:ss|yyyy年MM月dd日 等
     */
    public static String formatDataDIY(Date date, String style) {
        return new SimpleDateFormat(style).format(date);
    }

    /**
     * 将时间转成对应的style格式
     *
     * @param style yyyy-MM-dd|yyyyMMdd_hhmmss|yyyy-MM-dd hh:mm:ss|yyyy年MM月dd日 等
     */
    public static String formatDataDIY(long date, String style) {
        return new SimpleDateFormat(style).format(new Date(date));
    }

    /**
     * 将传入的时间转化为距离现在多少分，时
     *
     * @param time 多少ms
     * @return
     */
    public static String formatDataByNow(Long time) {
        if (time == null) {
            return "";
        }
        long now = System.currentTimeMillis() - time;
        now = now / 1000 / 60; //分
        if (now < 5) {
            return "刚刚";
        }
        if (now < 60) {
            return now + "分钟前";
        }
        now /= 60;  //小时
        if (now < 24) {
            return now + "小时前";
        }
        now /= 24; //天
        if (now < 7) {
            return now + "天前";
        }
        now /= 7; //周
        if (now < 5) {
            return now + "周前";
        }
        String fomatTime = formatDataDIY(new Date(time), "yyyy-MM-dd");
        return fomatTime;
    }

    public static boolean equals(String fieldNameOrig, String fieldNameDist) {
        if (isStringEmpty(fieldNameOrig) && isStringEmpty(fieldNameDist)) {
            return true;
        }
        return !isStringEmpty(fieldNameOrig) && !isStringEmpty(fieldNameDist) && fieldNameOrig.equals(fieldNameDist);
    }

    public static String getFormatTime(int seconds) {
        return getFormatHour(seconds / 3600) + ":" + getFormatMin((int) ((Math.ceil(seconds / 60.0f)) % 60));
    }

    public static String getFormatHour(int hour) {
        if (hour == 0) {
            return "00";
        } else {
            return hour < 10 ? "0" + hour : String.valueOf(hour);
        }
    }

    public static String getFormatMin(int min) {
        if (min == 0) {
            return "00";
        } else {
            return min < 10 ? "0" + min : String.valueOf(min);
        }
    }

    /**
     * 过滤掉字符串两端的双引号
     *
     * @param s
     * @return 过滤掉两端双引号的string
     */
    public static String filterQuotedString(String s) {
        int strLength = s.length();
        if (strLength <= 2) {
            return s;
        }

        if (String.valueOf(s.charAt(0)).equals("\"")
                && String.valueOf(s.charAt(strLength - 1)).equals("\"")) {
            return s.substring(1, strLength - 1);
        }
        return s;
    }

    /**
     * 在字符串两端添加双引号
     *
     * @param ssid
     * @return 添加双引号的string
     */
    public static String convertToQuotedString(String ssid) {
        return "\"" + ssid + "\"";
    }

    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 字符串转成ASCII
     *
     * @param value
     * @return
     */
    public static String strToAscII(String value) {
        StringBuilder sbu = new StringBuilder();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }

    /**
     * ASCII转成字符串
     *
     * @param value
     * @return
     */
    public static String ascIIToStr(String value) {
        StringBuilder sbu = new StringBuilder();
        if (value.startsWith("[")) {
            value = value.substring(1, value.length() - 1);
        }
        String[] chars = value.split(",");
        for (String aChar : chars) {
            if (aChar.startsWith("0")) {
                continue;
            }
            sbu.append((char) Integer.parseInt(aChar));
        }
        return sbu.toString();
    }

    /**
     * int数组转int数组，4个item为一个int数据
     *
     * @param array
     * @return
     */
    public static int[] arrayToIntArray(Object[] array) {
        int len = array.length;
        int[] intArray = new int[array.length / 4];
        for (int i = 0; i < intArray.length; i++) {
            Object[] intArray4 = new Object[4];
            System.arraycopy(array, 4 * i, intArray4, 0, 4);
            intArray[i] = arrayToInt(intArray4);
        }
        return intArray;
    }

    public static int arrayToInt(Object[] array) {
        return arrayToInt(array, false);
    }

    /**
     * int数组转int
     *
     * @param array int数组
     * @param reverse 是否反转，分大端小端，默认不反转
     * @return
     */
    public static int arrayToInt(Object[] array, boolean reverse) {
        int value = 0;
        if (array == null) {
            return value;
        }
        int len = array.length;
        for (int i = 0; i < len; i++) {
            if (reverse) {
                value += ((int)array[i]) << (i * 8);
            } else {
                value += ((int)array[i]) << ((len - i - 1) * 8);
            }
        }

        return value;
    }

    /**
     * int转byte数组
     *
     * @param value int
     * @return
     */
    public static byte[] intToArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) ((value >>> 8 * (4 - (i + 1))) & 0xFF);
        }
        return b;
    }
}
